package api

import (
	"github.com/gin-gonic/gin"
	"pkg/app"
	"pkg/e"
	"pkg/logging"
	"pkg/upload"
	"util"
)

// 上传图像
func UploadImage(c *gin.Context) {
	appG := app.Gin{C: c}
	file, image, err := c.Request.FormFile("image")
	if err != nil {
		logging.Error(err)
		appG.Response500(e.ERROR, nil)
		return
	}

	if image == nil {
		appG.Response400(nil)
		return
	}

	imageName := upload.GetImageName(image.Filename)
	fullPath := upload.GetImageFullPath()
	savePath := upload.GetImagePath()
	src := fullPath + imageName

	// 检查图像文件扩展名 .jpg,.jpeg,.png 和 文件大小 5MB
	if !upload.CheckImageExt(imageName) || !upload.CheckImageSize(file) {
		logging.Error(err)
		appG.Response400code(e.ERROR_UPLOAD_CHECK_IMAGE_FORMAT, nil)
		return
	}

	// 创建目录
	err = util.CheckFullPath(fullPath)
	if err != nil {
		logging.Error(err)
		appG.Response500(e.ERROR_UPLOAD_CHECK_IMAGE_FAIL, nil)
		return
	}

	// 保存
	if err := c.SaveUploadedFile(image, src); err != nil {
		logging.Error(err)
		appG.Response500(e.ERROR_UPLOAD_SAVE_IMAGE_FAIL, nil)
		return
	}

	// 返回上传成功路径
	data := map[string]string{
		e.Image_url:      upload.GetImageFullUrl(imageName),
		e.Image_save_url: savePath + imageName,
	}
	appG.Response200(data)
}
